package ebj.common.io.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

public class GetAllFilesByType {
    public static void main(String[] args) throws IOException {
        String baseDir = "P:/私有项目开发/素材/素材";
        String targetDir = baseDir + "/imgs/";
        File base = new File(baseDir);

        Files.newDirectoryStream(Paths.get(baseDir),
                path -> path.toString().endsWith(".xml")).forEach(
                System.err::println);

        // Files.list(Paths.get(targetDir))
        // .filter(Files::isDirectory)
        // .forEach(System.out::println);

        Set<String> imgSuffixSet = Sets.newHashSet();
        imgSuffixSet.add(".jpg");
        imgSuffixSet.add(".png");
        imgSuffixSet.add(".jpeg");
        imgSuffixSet.add(".gif");
        imgSuffixSet.add(".ico");
        imgSuffixSet.add(".bmp");
        listFilesByType(base, imgSuffixSet, targetDir);
    }

    /**
     * 删除文件、目录(含非空目录)
     * 
     * @param file
     * @return 
     * @return
     * @throws IOException 
     */
    private static void listFilesByType(File file, Set<String> suffixes, String targetDir) throws IOException {
        File[] files = file.listFiles();
        if (files != null){
            for (File f : files) {
                listFilesByType(f, suffixes, targetDir);
            }
        }
        if (file.isFile()) {
            String file_name = file.getAbsolutePath();
            if (suffixes.contains(file_name.substring(file_name.lastIndexOf("."), file_name.length()))) {
                copyToTarget(file_name, targetDir);
            }
        }
    }
    
    private static void copyToTarget(String srcFilePath, String targetDir) throws IOException {
        File file = new File(srcFilePath);
        try {
            Files.copy(Paths.get(srcFilePath), Paths.get(targetDir + file.getName()));
        } catch (Exception e) {
            if (e.getClass().getSimpleName().equalsIgnoreCase("FileAlreadyExistsException")) {
                String name = file.getName();
                String substring = name.substring(0, name.lastIndexOf("."));
                String substring2 = name.substring(name.lastIndexOf("."), name.length());
                Files.copy(Paths.get(srcFilePath), Paths.get(targetDir + substring + "." + Calendar.getInstance().getTimeInMillis() + substring2));
            }
        }
    }
}
